<template>
	<div class="article-manager video-icon form-submit" id="shopp-manager">
		<Modal v-model="innerVisible" :title="modalTitle" :width="900" @on-ok="handleOk"
			@on-cancel="handleClose">
			<Form ref="formDynamic" :model="formDynamic" class="attrFrom" @submit.native.prevent :rules="rules">
				<Row :gutter="24">

					<Col span="24" v-if="this.customerId == 0">
					<a @click="addProduct()" size="small"><Button type="primary"
							icon="ios-add-circle-outline">{{$t('page.customer.select_customer')}}</Button></a>
					</Col>
					<Col span="24">
					<Col span="24" class="mb15">
					<FormItem :label="$t('page.customer.visiting_clients')+'：'" prop="customer_id" class="vertical-layout">
						<Input v-model="formDynamic.company" :placeholder="$t('page.customer.visiting_clients')" disabled />
					</FormItem>
					</Col>
					</Col>
					<Col span="24">
					<Col span="24" class="mb15">
					<FormItem :label="$t('page.customer.visit_time')+'：'" prop="visit_time" class="vertical-layout">
						<br>
						<div style="margin-top: 5px;"></div>
						<DatePicker type="datetime" v-model="formDynamic.visit_time" format="yyyy-MM-dd HH:mm"
							:placeholder="$t('page.customer.select_visit_time')" style="width: 200px" :options="datePickerOptions"
							@on-change="handleTimeChange" />
					</FormItem>
					</Col>
					</Col>
					<Col span="24">
					<Col span="24" class="mb15">
					<FormItem :label="$t('page.stock.note')+'：'" prop="remarks" class="vertical-layout">
						<Input v-model="formDynamic.remarks" type="textarea" :autosize="{ minRows: 6, maxRows: 10 }"
							:placeholder="$t('page.stock.note')" />
					</FormItem>
					</Col>
					</Col>
				</Row>
			</Form>
			<!-- 自定义底部按钮 -->
			<template #footer>
				<div class="custom-modal-footer">
					<Button type="primary" size="large" @click="submit">
						{{$t('page.product.submit')}}
					</Button>
				</div>
			</template>
		</Modal>

		<Modal v-model="productShow" scrollable :title="$t('page.product.add_customer')" :closable="true" width="70%" :footer-hide="true"
			:mask-closable="false">
			<Form ref="orderData" :model="productSearchsData" :label-width="labelWidth" :label-position="labelPosition"
				class="tabform" @submit.native.prevent>
				<div class="acea-row">
					<FormItem :label="$t('page.order.search')+'：'">
						<Input v-model="productSearchsData.company" placeholder="" element-id="item_name" clearable
							style="width:250px;">
						<WordCount :value="productSearchsData.company" :total="20" />
						</Input>
					</FormItem>
					<Button type="primary" @click="productSearchs" class="ml20">{{$t('page.order.search')}}</Button>
				</div>
			</Form>
			<div>
				<vxe-table border="inner" ref="xTable" class="mt25" :loading="loading" row-id="id" :radio-config="{
	            reserve: false,
	            checkMethod: disableCheckMethod, // 添加禁用检查方法
	            highlight: true,
				checkStrictly: true,
	          }" @checkbox-all="checkboxAll" @radio-change="radioChange" :data="productList"
					:row-class-name="rowClassName">
					<template #empty>
						<p class="empty-text">{{$t('page.product.no_data')}}</p>
					</template>
					<vxe-column type="radio" width="100" :check-method="disableCheckMethod"></vxe-column>
					<vxe-column field="id" title="ID" width="150"></vxe-column>
					<vxe-column field="company" :title="$t('page.customer.customer_name')" width="150">
					</vxe-column>
					<vxe-column field="email" :title="$t('page.customer.email')" min-width="150">
					</vxe-column>

					<vxe-column field="state" :title="$t('page.customer.location')" min-width="90">
					</vxe-column>
				</vxe-table>
				<div class="acea-row row-right page">
					<Page :total="total" :current="productSearchsData.page" @on-change="pageChange"
						:page-size="productSearchsData.limit" />
				</div>
			</div>

			<Button type="primary" @click="submitProduct()">{{$t('page.order.submit')}}</Button>
		</Modal>
	</div>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from "vuex";
	import {
		storeCustomerListApi,
		createStoreCustomreAccessApi,
		storeCustomerAccessDetailApi
	} from "@/api/storeCustomer";
	import {
		createActivityProductApi,
	} from '@/api/capital'
	import {
		productInfoApi,
		activityProductListInfo
	} from "@/api/product";
	export default {
		name: 'customerInfo',
		props: {
			visible: {
				type: Boolean,
				default: false
			},
			activityId: {
				type: Number,
				default: null
			},
			customerId: {
				type: Number,
				default: 0
			}
		},
		data() {
			return {
				loading: false,
				modal: false,
				innerVisible: false,
				productShow: false,
				total: 0,
				ids: 0,
				productSearchsData: {
					company: "",
					type: 1,
					activity_id: 0,
					page: 1,
					limit: 15,
				},
				images: [],
				urlList: [],
				others: [],
				productList: [],
				radioProduct: {
					skuList: []
				},
				checkPidList: [],
				formDynamic: {

				},
				datePickerOptions: {
					disabledDate(date) {
						// 禁用今天之前的日期
						const today = new Date();
						today.setHours(0, 0, 0, 0);
						return date && date.valueOf() < today.valueOf();
					},
					disabledTime(date) {
						// 如果是今天，禁用当前时间之前的时间
						if (date) {
							const now = new Date();
							const today = new Date();
							today.setHours(0, 0, 0, 0);

							// 检查是否是今天
							if (date.valueOf() >= today.valueOf() && date.valueOf() < today.valueOf() + 86400000) {
								return {
									disabledHours: () => {
										const hours = [];
										for (let i = 0; i < now.getHours(); i++) {
											hours.push(i);
										}
										return hours;
									},
									disabledMinutes: (selectedHour) => {
										if (selectedHour === now.getHours()) {
											const minutes = [];
											for (let i = 0; i < now.getMinutes(); i++) {
												minutes.push(i);
											}
											return minutes;
										}
										return [];
									}
								};
							}
						}
						return {};
					}
				},
				rules: {
					customer_id: [{
						required: true,
						message: "请选择客户",
						trigger: "blur"
					}, ],
					visit_time: [{
						required: true,
						validator: (rule, value, callback) => {
							if (!value) {
								callback(new Error('请选择来访时间'));
							} else {
								callback();
							}
						},
						trigger: 'change'
					}],
					remarks: [{
						required: true,
						message: "请填写备注",
						trigger: "blur"
					}, ],
				},
			};
		},
		watch: {
			visible(val) {
				this.innerVisible = val
				if (val) {
					this.handleClose();
					console.log("打开弹窗, 客户ID:", this.customerId);

					if (this.customerId > 0) {
						this.getDetail(this.customerId)
					} else {
						this.clearData();
					}
					// 可以用 this.activityId 去请求商品
					// this.getGoodList(this.activityId)
				}
			},
			innerVisible(val) {
				this.$emit("update:visible", val)
			},
			// 监听radioProduct变化，确保数据格式正确
			radioProduct: {
				handler(newVal) {
					if (newVal.skuList) {
						this.$nextTick(() => {
							this.initActivityStockData();
						});
					}
				},
				deep: true,
				immediate: true
			}
		},
		created() {},
		computed: {
			modalTitle() {
			            return this.customerId > 0 ? this.$t('page.product.edit') : this.$t('page.product.add');
			        },
			labelWidth() {
				return this.isMobile ? undefined : 120;
			},
			...mapState("admin/layout", ["isMobile", "menuCollapse"]),
			// 计算属性：格式化标签数据
			customerTags() {
				return this.customerData.tags || [];
			},
			labelPosition() {
				return this.isMobile ? "top" : "right";
			},
			goodsColumns() {
				return [{
						title: "ID",
						key: "id",
						width: 80
					},
					{
						title: "客户名称",
						key: "company"
					},
					{
						title: "地址",
						slot: "state",

					},
					{
						title: "邮箱",
						key: "email"
					}
				]
			},
			skuColumns() {
				return [{
						title: "SKU ID",
						key: "id",
						width: 80
					},
					{
						title: $t('page.product.specification'),
						key: "suk"
					},
					{
						title: $t('page.product.original_price'),
						key: "price"
					},
					{
						title: $t('page.activity.event_price_title'),
						key: "activity_price",
						slot: "activity_price"
					},
					{
						title: $t('page.stock.warehouse'),
						key: "warehouse",
						slot: "warehouse"
					},
					{
						title: $t('page.stock.stock'),
						key: "stock",
						slot: "stock"
					},
					{
						title: $t('page.activity.event_stock_title'),
						key: "activity_stock",
						slot: "activity_stock"
					}
				]
			}
		},
		methods: {
			handleTimeChange(time) {
				const now = new Date();

				// 将选择的时间转换为本地时间进行比较
				const selectedTime = new Date(time);
				console.log("now", now);
				console.log("selectedTime", selectedTime);
				console.log("selectedTime.valueOf()", selectedTime.valueOf());
				console.log("now.valueOf()", now.valueOf());

				if (time && selectedTime.valueOf() < now.valueOf()) {
					this.$Message.error('到访时间不能早于当前时间');
					this.formDynamic.visit_time = '';
				}
			},
			getDetail(id) {
				storeCustomerAccessDetailApi(id)
					.then((res) => {
						this.formDynamic = res.data.info;
					})
					.catch((res) => {
						this.$Message.error(res.msg);
					});
			},
			clearData() {
				this.formDynamic = {}
			},
			// 提交前确保数据格式正确
			submit() {
				// 格式化日期函数，添加秒部分
				const formatDate = (date) => {
					if (!date) return '';

					// 如果是 Date 对象
					if (date instanceof Date) {
						const year = date.getFullYear();
						const month = String(date.getMonth() + 1).padStart(2, '0');
						const day = String(date.getDate()).padStart(2, '0');
						const hours = String(date.getHours()).padStart(2, '0');
						const minutes = String(date.getMinutes()).padStart(2, '0');
						const seconds = String(date.getSeconds()).padStart(2, '0');
						return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
					}

					// 如果是字符串，添加秒部分
					if (typeof date === 'string') {
						// 如果已经是完整格式，直接返回
						if (date.length === 19) return date;
						// 如果只有日期部分，添加时间
						if (date.length === 10) return `${date} 00:00:00`;
						// 如果只有小时和分钟，添加秒
						if (date.length === 16) return `${date}:00`;
					}

					return date.toString();
				};
				let customer_access_id = 0;
				if (this.customerId > 0) {
					customer_access_id = this.customerId
				}
				let data = {
					id: customer_access_id,
					customer_id: this.formDynamic.customer_id,
					visit_time: formatDate(this.formDynamic.visit_time),
					remarks: this.formDynamic.remarks,
				}

				console.log("格式化后的data", data)

				let isValid = true
				if (!data.customer_id || data.customer_id <= 0) {
					this.$Message.error(`请选择来访客户`);
					isValid = false;
				}
				if (!data.visit_time || data.visit_time.length <= 0) {
					this.$Message.error(`请选择来访时间`);
					isValid = false;
				}
				if (!data.remarks || data.remarks.length <= 0) {
					this.$Message.error(`请填写备注`);
					isValid = false;
				}

				if (isValid) {
					createStoreCustomreAccessApi(data)
						.then((res) => {
							this.$Message.success(res.msg);
							this.innerVisible = false
							this.$emit('success')
						})
						.catch((res) => {
							this.$Message.error(res.msg);
						});
				}
			},

			//分页
			pageChange(page) {
				this.productSearchsData.page = page;
				this.getProductList();
			},
			radioChange({
				row
			}) {
				console.log("选中的行：", row)
				this.radioProduct = row
				this.formDynamic.customer_id = row.id
				this.formDynamic.company = row.company
				console.log("选中的行radioProduct：", this.radioProduct)
			},
			rowClassName({
				row
			}) {
				if (row.stock === 0 || row.is_disable === 1) {
					return 'row-disabled';
				}
				return '';
			},
			handleClose() {
				this.radioProduct = {}
			},

			checkboxAll() {
				// 获取选中当前值
				let obj2 = this.$refs.xTable.getCheckboxRecords(true);
				// 获取之前选中值
				let obj = this.$refs.xTable.getCheckboxReserveRecords(true);
				if (this.isAll == 0 && this.checkPidList.length <= obj.length && !this.isCheckBox) {
					obj = [];
				}
				obj = obj.concat(obj2);
				let ids = [];
				obj.forEach((item) => {
					ids.push(parseInt(item.id))
				})
				this.checkPidList = ids;
				if (!obj2.length) {
					this.isCheckBox = false;
				}
			},
			// 禁用勾选方法
			disableCheckMethod({
				row
			}) {
				// 当库存为0时禁用勾选
				if (row.stock == 0 || row.is_disable == 1) {
					return false;
				} else {
					return true;
				}
			},
			productSearchs() {
				this.productSearchsData.page = 1
				this.getProductList()
			},

			submitProduct() {
				this.productShow = false
			},
			//添加产品
			addProduct() {
				this.productShow = true
				this.getProductList();
			},
			getProductList() {
				this.loading = true;
				this.productList = [];
				this.productSearchsData.activity_id = this.activityId
				storeCustomerListApi(this.productSearchsData).then((res) => {
					console.log("data.list", res.data.list)
					res.data.list.forEach(item => {
						this.productList.push({
							id: item.id,
							state: item.state,
							company: item.company,
							email: item.email,
						})
					})
					this.total = res.data.count;
					this.loading = false;
					// this.initActivityStockData(); // 初始化活动库存数据
				}).catch((err) => {
					this.loading = false;
					this.$Message.error(err.msg);
				})
			},
			handleOk() {
				this.$emit('update:modalVisible', false);
				// 处理确认逻辑
			},


			closeModal() {
				this.innerVisible = false
			}
		}
	};
</script>

<style scoped>
	/* 全局样式 */
	.customer-info-modal {
		padding: 24px;
	}

	/* 统计卡片样式 */
	.stats-cards {
		display: grid;
		grid-template-columns: repeat(4, 1fr);
		gap: 16px;
		margin-bottom: 24px;
	}

	.stat-card {
		background: #ffffff;
		border-radius: 8px;
		padding: 16px;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
		transition: all 0.3s ease;
		border: 1px solid #ebedf0;
	}

	.stat-card:hover {
		box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
		transform: translateY(-2px);
	}

	.card-value {
		font-size: 16px;
		font-weight: 600;
		color: #1d2129;
		margin-bottom: 4px;
	}

	.card-label {
		font-size: 14px;
		color: #86909c;
	}

	/* 主要内容区域 */
	.main-content {
		display: flex;
		gap: 24px;
	}

	/* 订单历史区域 */
	.order-history {
		flex: 2;
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16px;
	}

	.section-title {
		font-size: 18px;
		font-weight: 500;
		color: #1d2129;
	}

	.order-card {
		background: #ffffff;
		border-radius: 8px;
		padding: 16px;
		margin-bottom: 16px;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
		border: 1px solid #ebedf0;
		transition: all 0.3s ease;
	}

	.order-card:hover {
		box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
	}

	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 12px;
	}

	.order-meta {
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.order-number {
		font-size: 16px;
		font-weight: 500;
		color: #1d2129;
	}

	.order-date {
		font-size: 14px;
		color: #86909c;
	}

	.order-status {
		padding: 4px 8px;
		border-radius: 4px;
		font-size: 14px;
		font-weight: 500;
	}

	.status-pending {
		background: #fff7e6;
		color: #fa8c16;
	}

	.order-customer {
		font-size: 14px;
		color: #4e5969;
		margin-bottom: 12px;
	}

	.order-items {
		margin-bottom: 12px;
	}

	.order-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 8px 0;
		border-bottom: 1px solid #f2f3f5;
	}

	.order-item:last-child {
		border-bottom: none;
	}

	.product-info {
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.product-quantity {
		color: #86909c;
	}

	.product-name {
		color: #1d2129;
	}

	.product-price {
		font-weight: 500;
		color: #1d2129;
	}

	.order-total {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		gap: 8px;
		font-size: 16px;
		font-weight: 500;
		color: #1d2129;
	}

	/* 客户信息区域 */
	.customer-profile {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 16px;
	}

	.profile-card {
		background: #ffffff;
		border-radius: 8px;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
		border: 1px solid #ebedf0;
		transition: all 0.3s ease;
	}

	.profile-card:hover {
		box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
	}

	.card-header {
		padding: 16px;
		border-bottom: 1px solid #f2f3f5;
	}

	.card-title {
		font-size: 16px;
		font-weight: 500;
		color: #1d2129;
	}

	.card-body {
		padding: 16px;
	}

	.info-row {
		display: flex;
		align-items: center;
		margin-bottom: 8px;
	}

	.info-label {
		width: 140px;
		color: #86909c;
	}

	.info-value {
		color: #1d2129;
	}

	.company-name {
		font-size: 16px;
		font-weight: 500;
		color: #1d2129;
		margin-bottom: 8px;
	}

	.credit-value {
		font-size: 16px;
		color: #1d2129;
	}

	.tag-list {
		display: flex;
		flex-wrap: wrap;
		gap: 8px;
	}

	.ivu-btn-ghost {
		color: #fff;
		background: #161515 !important;
	}

	.tag {
		padding: 4px 8px;
		background: #f2f3f5;
		border-radius: 4px;
		font-size: 14px;
		color: #4e5969;
	}

	.view-all-link {
		float: right;
		color: #4c4e51;
		/* 正常状态颜色 */
		cursor: pointer;
		/* 鼠标变成手型 */
		transition: color 0.2s;
		/* 添加颜色过渡效果 */
	}

	.view-all-link:hover {
		color: #000000;
		/* 悬停状态颜色 */
		text-decoration: underline;
		/* 可选：添加下划线增强交互感 */
	}

	/* 灰色不可选行样式 */
	.row-disabled {
		background-color: #f5f5f5 !important;
		color: #999 !important;
		cursor: not-allowed;
	}
</style>